package com.mokairui.basic.threadsafe;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Vector;

/**
 * @author Mokairui
 * @Description 模拟卖票的场景,此测试的临界区是sell方法，共享变量为count
 * @Since 2021/6/13
 */
@Slf4j(topic = "c.ExerciseSell")
public class ExerciseSell {
    public static void main(String[] args) throws InterruptedException {
        // 模拟多人买票
        TicketWindow window = new TicketWindow(1000);

        // 所有的线程集合
        List<Thread> threadList = new ArrayList<>();
        // 卖出的票数统计
        List<Integer> amountList = new Vector<>();
        for (int i = 0; i < 2000; i++) {
            Thread thread = new Thread(() -> {
                // 在这里多个线程中同时对sell方法中的count进行操作，所以临界去为sell方法，共享变量是count
                int amount = window.sell(randomAmount());
                try {
                    Thread.sleep(randomAmount());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                amountList.add(amount);
            });
            threadList.add(thread);
            thread.start();
        }

        // 等待所有线程都完成，在进行票数的统计
        for (Thread thread : threadList) {
            thread.join();
        }

        // 统计卖出的票数和余票数
        log.debug("余票:{}", window.getCount());
        log.debug("卖出的票数:{}", amountList.stream().mapToInt(Integer::intValue).sum());
        log.debug("总票数:{}", window.getCount() + amountList.stream().mapToInt(Integer::intValue).sum());
    }

    // Random 为线程安全
    static Random random = new Random();

    // 随机 1~5
    public static int randomAmount() {
        return random.nextInt(5) + 1;
    }
}

class TicketWindow {
    private int count;

    public TicketWindow(int count) {
        this.count = count;
    }

    // 获取余票的数量
    public int getCount() {
        return this.count;
    }

    // 买票,返回购票的数量，临界区
    public synchronized int sell(int count) {
        if (this.count > count) {
            this.count -= count;
            return count;
        } else {
            return 0;
        }
    }
}
